<template>
    <div>
        <el-card style="width: 100%">
            <template #header>
                <h3>个人信息</h3>
            </template>
            <table>
                <tr>
                    <td><span>头像：</span></td>
                    <td><el-image v-if="userData.avatarUrl" style="width: 100px; height: 100px"
                            :src="userData.avatarUrl" :preview-src-list="userData.avatarUrl" fit="fill" /></td>
                </tr>
                <tr>
                    <td><span>学号：</span></td>
                    <td>{{ userData.account }}</td>
                </tr>
                <tr>
                    <td><span>姓名：</span></td>
                    <td>{{ userData.userName }}</td>
                </tr>
                <tr>
                    <td><span>性别：</span></td>
                    <td>{{ userData.sex }}</td>
                </tr>
                <tr>
                    <td><span>年龄：</span></td>
                    <td>{{ userData.age }}</td>
                </tr>
                <tr>
                    <td><span>学校：</span></td>
                    <td>{{ userData.job }}</td>
                </tr>
                <tr>
                    <td><span>创建时间：</span></td>
                    <td>{{ dataFormat(userData.addTime) }}</td>
                </tr>
                <tr>
                    <td><span>修改时间：</span></td>
                    <td>{{ dataFormat(userData.updateTime) }}</td>
                </tr>
            </table>
            <template #footer>
                <el-button type="primary" @click="">
                        修改个人信息
                    </el-button>
        </template>
        </el-card>
        <!-- 修改操作 -->
        <el-drawer v-model="drawerForm" title="修改个人信息" direction="rtl" size="30%">
            <el-form ref="ruleFormRef" style="max-width: 600px" :model="userForm" :rules="rules" label-width="auto"
                class="demo-ruleForm" status-icon>
                <el-form-item label="项目图片" prop="image">
                <el-upload class="avatar-uploader" active="#" :limit="1" :show-file-list="false"
                    :before-upload="beforeAvatarUpload" :http-request="handleFileUpload">
                    <el-image v-if="userForm.avatarUrl" style="width: 100px; height: 100px" :src="userForm.avatarUrl"
                        :preview-src-list="userForm.avatarUrl" fit="fill" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="upadteUserData(userForm.avatarUrl)">
                        保存
                    </el-button>
                    <el-button @click="drawerForm = false">取消</el-button>
                </el-form-item>
            </el-form>
        </el-drawer>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
// element-plus导入组件
import { ElMessage, ElNotification } from 'element-plus';
import type { FormInstance, FormRules, UploadProps } from 'element-plus';
import { Plus,Edit } from '@element-plus/icons-vue';
// 后端接口
import { Upload } from '../../api/upload';
import { getById,updateUser } from '../../api/user';
import { getByIdUn } from '../../api/university';

import dayjs from "dayjs";

// 页面跳转
import { useRouter } from 'vue-router';
const router = useRouter();
const errorId = sessionStorage.getItem('userRoleId')+''
if(errorId == undefined || errorId == ''){
    sessionStorage.setItem('error','not')
    router.push("/LimitsAuthority")
}

const userData = reactive({
    id: 0,
    account: '',
    userName: '',
    sex: '',
    age: 0,
    job: '',
    addTime: '',
    updateTime: '',
    avatarUrl: '',
});
const getUserData = () => {
    getById({id: (Number)(sessionStorage.getItem("userId")+"")}).then((res: any) => {
        if (res.code == 2000) {
            userData.id = res.data.id
            userData.account = res.data.account
            userData.userName = res.data.userName
            if (res.data.sex == 2) {
                userData.sex = '男'
            } else {
                userData.sex = '女'
            }
            userData.age = res.data.age
            getByIdUn({id: res.data.job}).then((res: any) => {
                if (res.code == 2000) {
                    userData.job = res.data.universityName
                } else {
                    ElMessage.error(res.message);
                }
            })
            userData.addTime = res.data.addTime
            userData.updateTime = res.data.updateTime
            userData.avatarUrl = res.data.avatarUrl
        }else{
            ElMessage.error(res.message);
        }
    })
}
getUserData()
const upadteUserData = (headUrl: string) => {
    userForm.avatarUrl = headUrl
    userForm.id = (Number)(sessionStorage.getItem("userId") + '')
    updateUser(userForm).then((res: any) => {
        if (res.code == 2000) {
            ElNotification({
                title: '成功',
                message: '修改头像成功',
                type: 'success',
            });
            location.reload()
            getUserData()
        } else {
            ElMessage.error(res.message);
        }
    })
}
// 抽屉参数
const drawerForm = ref(false)
const openDrawer = (avatarUrl: string) => {
    drawerForm.value = true
    userForm.avatarUrl = avatarUrl
}
// 表单验证
interface RuleForm {
    id: number
    avatarUrl: string
}

const ruleFormRef = ref<FormInstance>()
const userForm = reactive<RuleForm>({
    id: 0,
    avatarUrl: '',
})

const rules = reactive<FormRules<RuleForm>>({
    avatarUrl: [
        { required: true, message: '请选择头像', trigger: 'blur' },
    ],
})
const handleFileUpload = (fileForm: any) => {
    console.log("_____" + fileForm.file)
    const fileData = new FormData();
    fileData.append('file', fileForm.file)
    fileData.append('userId', '1')
    Upload(fileData).then((res: any) => {
        if (res.code == 2000) {
            ElMessage.success(res.message)
            console.log(res)
            userForm.avatarUrl = res.data
            sessionStorage.setItem("userAvatarUrl", res.data)
        } else {
            ElMessage.error(res.message)
        }
    })
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    const validTypes = ['image/jpeg', 'image/png'];
    if (!validTypes.includes(rawFile.type)) {
        ElMessage.error('文件必须是 jpg 或 png 格式!');
        return false;
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('文件大小不能超过 2MB!');
        return false;
    }
    return true
}
// 时间格式化函数
const dataFormat = (data: any) => {
    return dayjs(data).format("YYYY-MM-DD HH:mm:ss");
}
</script>

<style scoped>
table tr td{
    padding: 20px;
}
/* 上传图片 */
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    text-align: center;
}
</style>